<template>
  <div class="brandWrapper">
    <el-select v-model="value" remote :remote-method="remoteMethod" :loading="loading" filterable :disabled="!editable" ref="select">
      <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
      </el-option>
    </el-select>
  </div>
</template>

<script lang="ts">
import {Vue, Emit, Watch, Component, Prop} from 'vue-property-decorator'
import masterModal from "../../../../../api/module/masterModal";
import {BrandResponseDto, CommonPageResponse} from "../../../../../utils/types";
import {fieldProps} from "../../MainDisplay/InfoPreview";
import {OptionType} from "../CommodityClassify/type";

@Component({
  model:{
    prop: "propValue",
    event: "update"
  }
})
export default class BrandSelect extends Vue {
  value:string = ""
  loading:boolean = false
  options:{label:string, value:string}[] = [] as any
  staticOption:{label:string, value:string}[] = [] as any
  first_render:boolean = true
  @Prop({default:{}})item!:fieldProps
  @Prop({default:true})editable!:boolean
  async remoteMethod(query:string){
    if(query !== ''){
      this.loading = true
      const res:CommonPageResponse<BrandResponseDto> = await masterModal.getBrandData({page:1, pageSize:30, keyword:query})
      this.loading =false
      if(res.code === 200 && res.data.records.length){
        this.options = res.data.records.map(item => {
          return {label:item.cnName, value:item.id.toString()}
        })
      const data:OptionType[] = this.options.concat(this.staticOption)
      const uniqueByValue:OptionType[] = Array.from(new Map(data.map(item => [item.value, item])).values());
      this.options = uniqueByValue
      }
    }else{
      this.options = []
    }
  }
  focus(){
    //@ts-ignore
    this.$refs.select.focus()
  }
  @Emit("update")
  valueChangeUpdate(value:string){
    return value
  }

  @Emit("change")
  changeUpdate(value:string){
    return value
  }

  @Watch("value", {immediate: true})
  onValueChange(newValue: string) {
    this.valueChangeUpdate(newValue)
    const labelValue = <string>this.options.find(item => item.value === newValue)?.label;
    if(labelValue){
      this.changeUpdate(labelValue)
    }
  }

  @Watch("item", {immediate: true, deep: true})
  onItemChange(newValue:fieldProps) {
    if(this.first_render && newValue.labelKey && newValue.value){
      this.staticOption = [{label: (newValue as any)[newValue.labelKey],value: newValue.value}]
      this.options = this.staticOption
      this.first_render = false
    }
    this.value = newValue.value
  }


}
</script>

<style scoped lang="scss">
.brandWrapper{
  ::v-deep .el-input__inner {
    height: 32px;
    border: none;
    padding: 0
  }
  ::v-deep .el-input.is-disabled .el-input__inner{
    background: unset !important;
    color: #606266
  }
}
</style>